<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/view/include/css-include.jsp"%>
<%@ include file="/view/include/jsp-include.jsp"%>
<%@ include file="/view/include/jquery-include.jsp"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>TMI</title>

<script type="text/javascript">
<%--============================= 전역변수 선언 ==========================--%>

//행추가
<%-- <tr id="dynamicDetailAddRow"> 에서 dynamicDetail 까지 중요함..조회, 초기화 시킬때 dynamicDetail으로 시작하는 ID 값 삭제 해줌 
(행추가와, 조회 후 한방에 처리할려면 ID값 다쓰면 귀찮아짐)

ex:
- 행추가는 dynamicDetailAddRow
- 조회 후 생성되는 ROW는dynamicDetailSearchRow 
등으로   dynamicDetail로 조회, 초기화시 한방에 지울 수 있게하자..
--%>
/* ordDetailTable에 view화면 호출, 행추가, 초기화 시 필요     */
 var dynamicAddRow = "<tr id='dynamicDetailAddRow'>"
					+"<td width='5%' >New</td>"
					+"<td width='10%' ><input type='text' class='inSTR95' name='goodsCode'  /></td>"
					+"<td width='12%' ><input type='text' class='inSTR95' name='goodsCode'  /></td>"
					+"<td width='10%' ><input type='text' class='inSTR95' name='goodsCode'  /></td>"
					+"<td width='25%'><input type='text' class='inSTR95' readonly onFocus='blur();' /></td>"
					+"<td width='10%'> <input type='text' class='inST97' /></td>"
					+"<td width='15%'> <input type='text' class='inSTR95' readonly onFocus='blur();'/></td>"
					+"<td width='10%'> <input type='button' class='btncss' value='DEL' onclick='deleteTmpRow(this);' ></td>"    //행 추가후  삭제 버튼 추가
					+"</tr>";

    <%--============================= window onload ==========================--%>

    $().ready(function() {

    	<%-- 달력 --%>
    	calendar.makeCalender("ordDate");
    	calendar.makeCalender("reqDate");
    	calendar.makeCalender("schDate");
    	
    	<%-- ordDetailTable에입력항목 생성 --%>
    	$("table[id='ordDetailTable']").append(dynamicAddRow);  // 전역변수로 잡아둔 값 셋팅
    	
    	<%-- 버튼설정 --%>
        /* 초기화버튼 */
    	$("#reSetBtn").bind("click",function(){
    	      $("form[name='orderFrm']").each(function(){
    	            this.reset();
    	      });
    	      
    	      //reSetValidete(); //벨류데이션 체크 초기화;
    	      $("#cnt").html("(0 / ");  // textarea 초기화
    	      $("#ordNo1").attr({        // ordNo1 입력가능하게
    	    	  onFocus : "",
    	    	  readonly: false
    	      });
    	      $("#saveStatus").val("SAVE");     //신규 입력 상태로 변경
    	      $("tr[id^='dynamicDetail']").remove(); //dynamicAddRow로 시작하는 ID 지움..(조회 후에 하단 그리드 맵핑하기전에 생성한 ROW와 조회ROW 지워주자..)
    	      $("table[id='ordDetailTable']").append(dynamicAddRow); // 지운 후 다시 입력항목 셋팅.. (css상 span id로하면 디자인깨짐, .html 로 하면 그리드 제목 까지 해줘야해서 귀찮음.. , 조회후에는 지워만주자)
    	});
    	      
    	/* textarea 체크 */
    	$("#remark").bind("keyup",function(){
    		textAreaKyUp(this);  //조회 직후에도 호출해야해서 function 으로 뺌.. 
    	});
    	    	
        /* DETAIL ROW 행추가 버튼 설정 */
        $("#detailAddRow").bind("click",function(){
        	$("table[id='ordDetailTable']").prepend(dynamicAddRow);  // 전역변수로 잡아둔 값 셋팅
        });
        
    	/* 오더번호 생성 */
        $("#ordNo1").bind("focusout",function(){  //ordNo2 조회
        	if( $("#saveStatus").val() =="SAVE" && $("#ordNo1").val() != ""){   //신규 일때만 조회
	            $.post('/getMaxOdrSeq.json', {
	            	     ordNo1 : $("#ordNo1").val()
	            	  },
	            function(data) { 
            		  if(data.ordNo2  == null || data.ordNo2 ==""){
            			  alert("Error!!");
            		  }else{
            			    $("#ordNo2").val( data.ordNo2 ); //조회한 오더 SEQ 값 입력
            		  }
	            });
        	}
        });
        
    	/* 저장버튼 */
    	$("#saveBtn").bind("click",function(){       
    		$("form[name='orderFrm']").submit();
    	});

    	/* 메인폼 서브밋 */
        $("form[name='orderFrm']").ajaxForm({
            dataType: "json",
            beforeSerialize: function($form, options) {
            	//return $("form[name='orderFrm']").valid();  jquery 벨류데이션 플러그인 사용시
                 if( !validation() ){       //화면 항목 점검 시작
                	return false;
                }
            },
            success:function(data) {
               if(data.result == true){
            	   alert("Complete the save");
            	   searchDataMaping(data);   //조회 데이터 맵핑 펑션
               }               
           },
           error:function(){alert("error!!");}
        }); 
        
    });
    
    <%--============================= function ==========================--%>
    
    /* 조회 펑션 */
    function view(ordNo1 , ordNo2){
    	$.post(
                '/getOrderView.json', {
                ordNo1 : "11111",//ordNo1,
                ordNo2 : "001"//ordNo2
                },
            function(data) {
               	searchDataMaping(data);    //DATA맵핑 
            });
    }
    
    /* odrDetail 삭제 펑션 */
    function delOdrDetail(idx , rowNum){
        if(confirm("Delete?")){
	        $.post(                                    //삭제Mothod 호출
	               '/delOdrDetail.json', {
	            	odrDetailSeq : idx    // 파라미터명 : 값
	                },
	          function(data) {
	                if(data.result == true){
	                	alert("OK!");
	                	$("#dynamicDetailSearchRow"+rowNum).remove();    // 삭제한ROW 삭제함..
	                }else{
	                	alert("error: error!!");
	                }
	       });	
        }
    }
    
    /* searchData 맵핑 */
    function searchDataMaping(data){
        var val = ""; 
        for(var v in data.resultMap) {       //상단 조회 결과 맵핑 조회return값이 한건임
            $("#"+v).val(data.resultMap[v]);
        }
        $("#ordNo1").attr({           //조회후 ID값 (ordNo1) 수정못하게 막음
            onFocus:"this.blur();", 
            readonly:true
        });
        
        //하단 그리드 맵핑
        var contents = "";
        $.each(data.resultDetailList, function(index){  // List로 받아온값 (여러건)
        	$("tr[id^='dynamicDetail']").remove(); //dynamicAddRow로 시작하는 ID 지움..(조회 후에 하단 그리드 맵핑하기전에 임의로 생성한 AddROW와 조회했던ROW 지워주자..)
        	
        	//(Detail 테이블에 조회결과 입히기 jquery말고 그냥 onclick 걸어줌.. (조회 후 del 번튼에 key값 param변수로 입력)
            var rowNum = index+1;

            contents += "<tr id='dynamicDetailSearchRow"+rowNum+"'>"      // ※주의 : id값 dynamicDetail... 으로 시작해야 한방에 지울 수 있음..    (TR ID는 조회건 삭제 후 ROW삭제에 사용)
                +'<td align="center" width="5%">'+rowNum+'</td>'
                +'<td align="right"  width="10%">'+this.prdtCode+'</td>'
                +'<td align="left"   width="40%">'+this.prdtDesc+'</td>'
                +'<td align="right"  width="10%">'+this.odrQy+'</td>'
                +'<td align="left"   width="15%">'+this.prdtUnit+'</td>'
                +'<td align="center" width="10%">'+this.odrDetailRm+'</td>'
                +'<td align="center  width="10%"">'
                +'<input type="button" class="btncss" value="Update" onclick="viewDialogOpen('+this.odrDetailSeq+' , \''+this.odrQy+'\',\''+this.odrDetailRm+'\')"/>'   //onclick= 업데이트다이얼 로그 ( 키값)
                +'<input type="button" class="btncss" value="DEL" onclick="delOdrDetail('+this.odrDetailSeq+','+rowNum+')"/>'+'</td>'   //onclick= 삭제 펑션 호출 ( 키값, 해당ROW값)
                +"</tr>";     
        });
        $("table[id='ordDetailTable']").append(contents);  // 조회 값 뿌리기
 
        $("#saveStatus").val("UPDATE"); // 상태값 UPDATE로 변경
        
    }
    
    <%--================================= FORM 컨트롤 ============================--%>
    /* 사용자가 추가한 행 삭제 */
    function deleteTmpRow(obj){
    	$(obj).parent().parent().remove();     // 사용자가 동적 생성한 ODR DETAIL ROW삭제
    }

    function validation(){

    	var ordNo1          = $("#ordNo1").val();
    	var ordDate         = $("#ordDate").val();
    	var reqDate         = $("#reqDate").val();
    	var schDate         = $("#schDate").val();
    	
    	if(ordNo1==null           || ordNo1=="") {   alert("order No: Required fields."); $("#ordNo1").focus(); return false; }
        if(ordNo1.length < 5) {   alert("order No: Enter the 5 characters"); $("#ordNo1").focus(); return false; }
        
        if( !isValidDate(ordDate,"Order Date") ){ $("#ordDate").focus(); return false; }
        if( !isValidDate(reqDate,"Requset Date") ){ $("#reqDate").focus(); return false; }
        if( !isValidDate(schDate,"Schedule Date") ){ $("#schDate").focus(); return false; }
/*     	var ordDate         = $("#ordDate").val();
    	var originCode      = $("#originCode").val();
    	var originName      = $("#originName").val();
    	var packingDesc     = $("#packingDesc").val();
    	var reqDate         = $("#reqDate").val();
    	var priceBase       = $("#priceBase").val();
    	var scheduleDate    = $("#scheduleDate").val();
    	var portOfLoadName  = $("#portOfLoadName").val();
    	var transMethodName = $("#transMethodName").val();
 */
        
    	
/*     	if(ordDate==null         || ordDate=="") { alert("ordDate 입려하시오."); $("#ordDate").focus(); return false; }
    	if(originCode==null      || originCode=="") { alert("originCode 입려하시오."); $("#originCode").focus(); return false; }
    	if(originName==null      || originName=="") { alert("originName 입려하시오."); $("#originName").focus(); return false; }
    	if(packingDesc==null     || packingDesc=="") { alert("packingDesc 입려하시오."); $("#packingDesc").focus(); return false; }
    	if(reqDate==null         || reqDate=="") { alert("reqDate 입려하시오."); $("#reqDate").focus(); return false; }
    	if(priceBase==null       || priceBase=="") { alert("priceBase 입려하시오."); $("#priceBase").focus(); return false; }
    	if(scheduleDate==null    || scheduleDate=="") { alert("scheduleDate 입려하시오."); $("#scheduleDate").focus(); return false; }
    	if(portOfLoadName==null  || portOfLoadName=="") { alert("portOfLoadName 입려하시오."); $("#portOfLoadName").focus(); return false; }
    	if(transMethodName==null || transMethodName=="") { alert("transMethodName 입려하시오."); $("#transMethodName").focus(); return false; }

    	if( !isValidDate(ordDate,"ordDate") ){ $("#ordDate").focus(); return false; }
        if( !isValidDate(reqDate,"reqDate") ){ $("#reqDate").focus(); return false; }
        if( !isValidDate(scheduleDate,"scheduleDate") ){ $("#scheduleDate").focus(); return false; }
        
 */    	
      return true;   	
    } 

    /* textarea 체크 */
    var oldStr;
    function textAreaKyUp(obj){
        var str = obj.value;
        if(str.length <= 1000){
            oldStr = str;
            contents = "("+str.length+" / ";
            $("#cnt").html(contents);
        }else{
            alert("제한된 문자열을 초과 했습니다.");
            $("#remark").val(oldStr);
        }
    };
    
    

    /*     
        // 기본폼 체크   jquery 벨류데이션 플러그인 사용시
        $().ready(function() {
            $("form[name='orderFrm']").validate({
                errorClass:"errorLeft",
                rules:{
                    ordNo1:{ required: true },
                    ordDate:{ required: true , dateISO: true},
                    originCode:{ required: true , number: true },
                    originName: {required: true},
                    packingDesc: {required: true},
                    reqDate:{ required: true , dateISO: true},
                    priceBase:{ required: true },
                    scheduleDate:{ required: true , dateISO: true},
                    portOfLoadName:{ required: true },
                    transMethodName:{ required: true }
                },
                messages:{
                    ordNo1:{ required: "필수 항목 입니다."},
                    ordDate:{ required: "필수 항목 입니다." , dateISO:"YYYY-MM-DD"},
                }
            });
        });
        
        // 벨류데이션 초기화
         function reSetValidete(){
            $("form[name='orderFrm']").validate().resetForm(); //벨류데이션 체크 초기화;
        }
       */  
       
    /************************************************************************/
    /*                          view POPUP , 리턴값처리                     */
    /************************************************************************/
    function viewDialogOpen(idx , qy , rm){
    	$("#pop_odrDetailSeq").val(idx);
        $("#pop_qy").val(qy);
        $("#pop_rm").val(rm);
        
        $("#viewDialog").dialog({
            modal:true, 
            width:300,
            title:"Detail Update"
        });
    }


    /* detail update*/
    function detailUpdate(){

        $.post("/detailUpdate.json",{
        	odrDetailSeq : $("#pop_odrDetailSeq").val(),
        	odrQy:         $("#pop_qy").val(),
        	odrDetailRm:   $("#pop_rm").val()
        },function(data){
            if(data.result == true){
            	$("#viewDialog").dialog("close");
            	view($("#ordNo1").val() , $("#ordNo2").val());
            }
        });
    }

</script>
</head>


<body>
<div class="wrap">
    <div class="pagetitle">
        <h1>STOCK MOVEMENT TO W/H</h1>
    </div>
    <div class="">
    <!-- 레이어 팝업시작 -->
        <div id="viewDialog" style="display: none; background: white;">
         <input type="hidden" id="pop_odrDetailSeq">
           <table class="TableST">
             <tr>
               <th>Quantity</th>
               <td><input type="text" name="pop_qy" id="pop_qy" class="inST50" maxlength="20"/></td>
              </tr>
             <tr>
               <th>Remarks</th>
               <td><input type="text" name="pop_rm" id="pop_rm" class="inST50" maxlength="20"/></td>
              </tr>
           </table>
            <div class="button">
               <span id="viewBtnType"></span>
               <img src="/images/web/cancle_btn01.gif"  onclick='javascript: detailUpdate();' style="cursor:hand;" alt="SAVE" />
           </div>   
       </div>
    <!-- 레이어 팝업끝 -->   
       
    <form name="orderFrm" method="post" action="/saveOrder.json"> <%--리턴값 json으로 설정 --%>
    <input type="hidden" id ="saveStatus" name="saveStatus" value="SAVE" />     <%-- 조회, 수정, 초기화, 최초 입력 시 필요 (최초, 초기화 후 = SAVE   ,  수정, 조회 후 = UPDATE)--%>
    
        <table class="TableST">
            <tr>
                <th>Order No</th>
                <td colspan="3">
                    <input type="text" class="inST10" id="ordNo1" name="ordNo1" maxlength="5" value=""/>
                    <input type="text" class="inSTR10" id="ordNo2" name="ordNo2" readonly onFocus="blur();" value=""/></td>
            </tr>
            <tr>
                <th>Order Date</th>
                <td colspan="3">
                    <input type="text" class="inST20" id="ordDate" name="ordDate"/>
            </tr>
            <span id="dynamicTr">
            <tr>
                <th>Shipper</th>
                <td colspan="2">
                    <input type="text" class="inSTR10" id="ordShipper" name="ordShipper" readonly onFocus="blur();" value=""/><img alt="Search" height="20" src="/images/web/btn_search.gif" align="absmiddle">
                    <input type="text" class="inSTR80" readonly onFocus="blur();" value=""/></td>
                <td><input type="text" class="inSTR50" readonly onFocus="blur();" value=""/></td>
            </tr>
            <tr>
                <th></th>
                <td><input type="text" class="inSTR95" readonly onFocus="blur();" value=""/></td>
                <td><input type="text" class="inSTR86" readonly onFocus="blur();" value=""/></td>
                <td><input type="text" class="inSTR90" readonly onFocus="blur();" value=""/></td>
            </tr>
            <tr>
                <th>Messrs</th>
                <td colspan="2">
                    <input type="text" class="inSTR10" id="ordMessrs" name="ordMessrs" readonly onFocus="blur();" value=""/><img alt="Search" height="20" src="/images/web/btn_search.gif" align="absmiddle">
                    <input type="text" class="inSTR80" readonly onFocus="blur();" value=""/></td>
                <td><input type="text" class="inSTR50" readonly onFocus="blur();" value=""/></td>
            </tr>
            <tr>
                <th></th>
                <td><input type="text" class="inSTR95" readonly onFocus="blur();" value=""/></td>
                <td><input type="text" class="inSTR86" readonly onFocus="blur();" value=""/></td>
                <td><input type="text" class="inSTR90" readonly onFocus="blur();" value=""/></td>
            </tr>
            <tr>
                <th>Notify Party</th>
                <td colspan="2">
                    <input type="text" class="inSTR10" id="ordNotify" name="ordNotify" readonly onFocus="blur();" value=""/><img alt="Search" height="20" src="/images/web/btn_search.gif" align="absmiddle">
                    <input type="text" class="inSTR80" readonly onFocus="blur();" value=""/></td>
                <td><input type="text" class="inSTR50" readonly onFocus="blur();" value=""/></td>
            </tr>
            <tr>
                <th></th>
                <td><input type="text" class="inSTR95" readonly onFocus="blur();" value=""/></td>
                <td><input type="text" class="inSTR86" readonly onFocus="blur();" value=""/></td>
                <td><input type="text" class="inSTR90" readonly onFocus="blur();" value=""/></td>
            </tr>
            </span>
            <tr>
                <th>Packing</th>
                <td colspan="3">
                    <input type="text" class="inST97" id="packing" name="packing" value=""/>
                </td>
            </tr>
            <tr>
                <th>Stored at</th>
                <td colspan="3">
                    <input type="text" class="inST97" id="packing" name="packing" value=""/>
                </td>
            </tr>
            <tr>
                <th>Loding</th>
                <td><input type="text" class="inST90" id="dispatch" name="dispatch" value=""></td>
                <th class="thST2">Destination</th>
                <td>
                    <input type="text" class="inST90" id="destination" name="destination" value=""/>
                </td>
            </tr>
            <tr>
                <th>Sailing on</th>
                <td>
                    <input type="text" class="inST80" id="reqDate" name="reqDate" value=""/>
                </td>
                <th class="thST2">Net-Weight</th>
                <td>
                    <input type="text" class="inST90" id="priceBase" name="priceBase" value=""/>
                </td>
            </tr>
            <tr>
                <th>Carrior</th>
                <td><input type="text" class="inST90" id="dispatch" name="dispatch" value=""></td>
                <th class="thST2">Gross-Weight</th>
                <td>
                    <input type="text" class="inST90" id="destination" name="destination" value=""/>
                </td>
            </tr>
            <tr>
                <th>Carton</th>
                <td width="290px"><input type="text" class="inST90" id="dispatch" name="dispatch" value=""></td>
                <th class="thST2">Cubic-M</th>
                <td>
                    <input type="text" class="inST90" id="destination" name="destination" value=""/>
                </td>
            </tr>
        </table>
        <br />
        <div class="bo_btn">
            <input type="button" class="btncss" align="right" value="Add" id="detailAddRow"/>
        </div>
        <div class="taHeadW">
            <table class="TableST2Head" >
                <tr>
                    <th width="5%">No</th>
                    <th width="10%">Batch</th>
                    <th width="12%" align="Center">Expired Date</th>
                    <th width="10%">Code</th>
                    <th width="28%">Description</th>
                    <th width="10%">Quantity</th>
                    <th width="15%">Unit</th>
                    <th width="10%">del</th>
                </tr>
            </table>
        </div>
        <div class="taBodyW">
            <table class="TableST2Body" id="ordDetailTable">
            </table>
        </div>    
        <br />
        <table class="TableST3">
            <tr>
                <th width="20%">Remarks<br><span id="cnt">(0 / </span>1000)</th>
                <td><textarea class="teST80" wrap="virtual" id="remark" name="remark"></textarea></td>
            </tr>
        </table>
    </div>
    <div class="bo_btn">
        <ul class="btnst"><li class="a"><a href="#" id="reSetBtn" >RESET</a></li></ul>
        <ul class="btnst"><li class="a"><a href="javascript:view();" id="searchBtn" >Search(임시)</a></li></ul>
        <ul class="btnst"><li class="a"><a href="#" id="saveBtn" >SAVE</a></li></ul>
    </div>
        </form>
</div>
</body>
</html>